<template>
  <div class="custom-code-generation">
    <h3>自定义代码生成工具</h3>
    
    <!-- 基本信息配置 -->
    <a-card title="基本信息配置" style="margin-bottom: 20px;">
      <a-form :model="formState" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="页面代码 (pageCode)" name="pageCode">
              <a-input v-model:value="formState.pageCode" placeholder="请输入页面代码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="生成类型" name="generationType">
              <a-select 
                v-model:value="formState.generationType" 
                placeholder="请选择生成类型"
                :options="generationTypeOptions"
                :loading="generationTypeLoading"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 数据源配置 -->
    <a-card title="数据源配置" style="margin-bottom: 20px;">
      <!-- 列表页配置 -->
      <ListDataSourceConfig 
        v-if="formState.generationType === 'list'"
        v-model="dataSourceConfig"
      />
      
      <!-- 详情页配置 -->
      <DetailDataSourceConfig 
        v-else-if="formState.generationType === 'detail'"
        v-model="dataSourceConfig"
      />
      
      <!-- 表单页配置 -->
      <ListDataSourceConfig 
        v-else-if="formState.generationType === 'modal_table'"
        v-model="dataSourceConfig"
      />

      <FormDataSourceConfig 
        v-else-if="formState.generationType === 'modal_form'"
        v-model="dataSourceConfig"
      />


      <ListDetailDataSourceConfig 
        v-else-if="formState.generationType === 'list_detail'"
        ref="listDetailRef"
        v-model="dataSourceConfig"
      />


      <MultiTabDetailDataSourceConfig 
        v-else-if="formState.generationType === 'multi_tab_detail'"
        v-model="dataSourceConfig"
      />

      
    </a-card>
    
    <!-- 操作按钮 -->
    <div style="text-align: center; margin-top: 20px;">
      <!-- <a-button type="default" size="large" @click="previewData" style="margin-right: 20px;">
        预览数据
      </a-button> -->
      <a-button 
        type="primary" 
        size="large" 
        @click="saveConfig"
        style="margin-right: 20px;"
      >
        保存配置
      </a-button>
      <a-button 
        type="default" 
        size="large" 
        @click="showPreviewCode"
        :loading="generateLoading"
        style="margin-right: 20px;"
      >
        <template #icon>
          <EyeOutlined />
        </template>
        预览代码
      </a-button>
      <!-- <a-button 
        type="primary" 
        size="large" 
        @click="showVersionSelection"
        :loading="generateLoading"
        style="margin-right: 20px;"
      >
        <template #icon>
          <DownloadOutlined />
        </template>
        生成并下载代码
      </a-button> -->
    </div>
    
    <!-- 数据预览弹窗 -->
    <a-modal
      v-model:open="previewVisible"
      title="数据预览"
      width="60%"
      :footer="null"
    >
      <div style="max-height: 60vh; overflow-y: auto;">
        <pre>{{ previewDataContent }}</pre>
      </div>
    </a-modal>
    
    <!-- 代码预览弹窗 -->
    <CodePreviewModal 
      v-model:open="previewCodeVisible"
      :files="previewCodeFiles"
      @download-all="downloadGeneratedCode"
    />
    
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch,nextTick  } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import {  EyeOutlined } from '@ant-design/icons-vue'
import ListDataSourceConfig from '../components/DataSourceConfig/ListDataSourceConfig.vue'
import DetailDataSourceConfig from '../components/DataSourceConfig/DetailDataSourceConfig.vue'
import FormDataSourceConfig from '../components/DataSourceConfig/FormDataSourceConfig.vue'
import ListDetailDataSourceConfig from '../components/DataSourceConfig/ListDetailDataSourceConfig.vue'
import MultiTabDetailDataSourceConfig from '../components/DataSourceConfig/MultiTabDetailDataSourceConfig.vue'
import LogManager from '../logUtils.js'
import {config} from '../config.js'
import CodePreviewModal from '../components/CodePreviewModal.vue'

// 路由
const route = useRoute()
const router = useRouter()

// 表单状态
const formState = reactive({
  pageCode: '',
  generationType: undefined
})

// 生成类型选项
const generationTypeOptions = ref([])

// 生成类型加载状态
const generationTypeLoading = ref(false)

// 数据源配置
const dataSourceConfig = ref({})

// 预览弹窗可见性
const previewVisible = ref(false)

// 预览数据内容
const previewDataContent = ref('')

// 生成代码按钮加载状态
const generateLoading = ref(false)

// 代码预览相关状态
const previewCodeVisible = ref(false)
const previewCodeFiles = ref([])

// 监听生成类型变化，重置数据源配置
watch(() => formState.generationType, (newType, oldType) => {
  if (newType !== oldType) {
    dataSourceConfig.value = {}
  }
})

// 获取生成类型选项
const fetchGenerationTypes = async () => {
  generationTypeLoading.value = true
  try {
    const response = await fetch(`${config.domain}/api/template-management`)
    const result = await response.json()
    
    if (result.success) {
      // 将模板数据转换为选择框选项
      generationTypeOptions.value = result.data.map(item => ({
        label: item.title,
        value: item.key
      }))
    } else {
      message.error(result.message || '获取生成类型失败')
      // 使用默认选项
      generationTypeOptions.value = [
        { label: '列表页', value: 'list' },
        { label: '详情页', value: 'detail' },
        { label: '弹框(列表)', value: 'modal_table' },
        { label: '弹框(表单)', value: 'modal_form' }
      ]
    }
  } catch (error) {
    console.error('获取生成类型失败:', error)
    message.error('获取生成类型失败: ' + error.message)
    // 使用默认选项
    generationTypeOptions.value = [
      { label: '列表页', value: 'list' },
      { label: '详情页', value: 'detail' },
      { label: '弹框(列表)', value: 'modal_table' },
      { label: '弹框(表单)', value: 'modal_form' }
    ]
  } finally {
    generationTypeLoading.value = false
  }
}

// 显示代码预览
const showPreviewCode = async () => {
  if (!formState.pageCode) {
    message.warning('请输入页面代码')
    return
  }
  
  if (!formState.generationType) {
    message.warning('请选择生成类型')
    return
  }
  
    previewCode()
}

// 预览代码函数
const previewCode = async () => {
  // 组织数据
  const result = {
    pageCode: formState.pageCode,
    generationType: formState.generationType,
    dataSourceConfig: dataSourceConfig.value
  }
  
  // 显示加载状态
  generateLoading.value = true
  
  try {
    // 创建请求数据
    const requestData = result    
    // 调用后端接口生成代码预览
    const response = await fetch(`${config.domain}/api/generate-code-preview`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })
    
    const resultData = await response.json()
    
    if (resultData.success) {
      // 设置预览文件
      previewCodeFiles.value = resultData.files
      
      // 显示预览弹窗
      previewCodeVisible.value = true
      
      // 记录日志
      await LogManager.logAction('预览代码', 1, {
        pageCode: formState.pageCode,
        generationType: formState.generationType,
        fieldsCount: getFieldsCount(dataSourceConfig.value),
        fields: getFieldsList(dataSourceConfig.value)
      })
    } else {
      message.error(resultData.error || '代码预览生成失败')
    }
  } catch (error) {
    console.error('代码预览生成失败:', error)
    message.error('代码预览生成失败: ' + error.message)
  } finally {
    generateLoading.value = false
  }
}

// 下载生成的代码
const downloadGeneratedCode = async () => {
  // 组织数据
  const result = {
    pageCode: formState.pageCode,
    generationType: formState.generationType,
    dataSourceConfig: dataSourceConfig.value
  }
  
  // 显示加载状态
  generateLoading.value = true
  
  try {
    // 创建请求数据
    const requestData = result    
    // 记录日志
    await LogManager.logAction('生成代码', 1, {
      pageCode: formState.pageCode,
      generationType: formState.generationType,
      fieldsCount: getFieldsCount(dataSourceConfig.value),
      fields: getFieldsList(dataSourceConfig.value)
    })
    
    // 调用后端接口生成代码
    const response = await fetch(`${config.domain}/api/generate-code-from-data`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })
    
    if (response.ok) {
      // 获取文件名
      const disposition = response.headers.get('Content-Disposition')
      let filename = 'generated-code.zip'
      if (disposition && disposition.indexOf('attachment') !== -1) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        const matches = filenameRegex.exec(disposition)
        if (matches != null && matches[1]) {
          filename = matches[1].replace(/['"]/g, '')
        }
      }
      
      // 创建下载链接
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      // 提示成功
      message.success('代码生成成功')
    } else {
      const errorText = await response.text()
      console.error('代码生成失败:', errorText)
      message.error('代码生成失败: ' + errorText)
    }
  } catch (error) {
    console.error('代码生成失败:', error)
    message.error('代码生成失败: ' + error.message)
  } finally {
    generateLoading.value = false
  }
}

// 预览数据函数
const previewData = () => {
  // 组织数据
  const result = {
    pageCode: formState.pageCode,
    generationType: formState.generationType,
    dataSourceConfig: dataSourceConfig.value
  }
  
  // 设置预览内容
  previewDataContent.value = JSON.stringify(result, null, 2)
  
  // 显示弹窗
  previewVisible.value = true
}

// 获取字段数量
const getFieldsCount = (config) => {
  let count = 0
  if (config.queryFields) count += config.queryFields.length
  if (config.listFields) count += config.listFields.length
  if (config.formFields) count += config.formFields.length
  if (config.headerFields) count += config.headerFields.length
  return count
}

// 获取字段列表
const getFieldsList = (config) => {
  const fields = []
  if (config.queryFields) fields.push(...config.queryFields.map(f => f.fieldName))
  if (config.listFields) fields.push(...config.listFields.map(f => f.fieldName))
  if (config.formFields) fields.push(...config.formFields.map(f => f.fieldName))
  if (config.headerFields) fields.push(...config.headerFields.map(f => f.fieldName))
  return fields
}


// 保存配置
const saveConfig = () => {
  if (!formState.pageCode) {
    message.warning('请输入页面代码')
    return
  }
  
  if (!formState.generationType) {
    message.warning('请选择生成类型')
    return
  }
  
  try {
    // 获取现有的配置
    const configs = JSON.parse(localStorage.getItem('savedCodeConfigs') || '[]')
    
    // 构造配置对象
    const configToSave = {
      id: Date.now().toString(), // 使用时间戳作为唯一ID
      pageCode: formState.pageCode,
      generationType: formState.generationType,
      dataSourceConfig: dataSourceConfig.value,
      createTime: new Date().toISOString()
    }
    
    // 如果是编辑状态，则更新配置
    const existingConfigIndex = configs.findIndex(c => c.id === route.query.id)
    if (existingConfigIndex >= 0) {
      // 保留原始创建时间
      configToSave.createTime = configs[existingConfigIndex].createTime
      configToSave.id = route.query.id
      configs[existingConfigIndex] = configToSave
      message.success('配置更新成功')
    } else {
      configs.push(configToSave)
      message.success('配置保存成功')
    }
    
    // 保存到localStorage
    localStorage.setItem('savedCodeConfigs', JSON.stringify(configs))
  } catch (error) {
    console.error('保存配置失败:', error)
    message.error('保存配置失败: ' + error.message)
  }
}

// 加载配置
const loadConfig = (configId) => {
  try {
    const configs = JSON.parse(localStorage.getItem('savedCodeConfigs') || '[]')
    const configToLoad = configs.find(c => c.id === configId)
    
    if (configToLoad) {
      formState.pageCode = configToLoad.pageCode
      formState.generationType = configToLoad.generationType
      
      // 使用 nextTick 确保子组件能正确接收到更新后的数据
      nextTick(() => {
        dataSourceConfig.value = configToLoad.dataSourceConfig || {}
      })
    } else {
      message.warning('未找到指定的配置')
    }
  } catch (error) {
    console.error('加载配置失败:', error)
    message.error('加载配置失败: ' + error.message)
  }
}

// 组件挂载时获取生成类型选项
onMounted(() => {
  fetchGenerationTypes()
    // 如果有id参数，则加载配置
    const configId = route.query.id
  if (configId) {
    loadConfig(configId)
  }
  })
</script>

<style scoped>
.custom-code-generation {
  padding: 20px;
}

.empty-tip {
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 16px;
}
</style>